"use client"

import type React from "react"

import { useAuth } from "@/lib/auth-context"
import { useRouter } from "next/navigation"
import { useEffect } from "react"

interface AuthGuardProps {
  children: React.ReactNode
  requiredPermission?: {
    resource: string
    action: string
  }
  requiredRole?: string
  fallback?: React.ReactNode
}

export function AuthGuard({ children, requiredPermission, requiredRole, fallback }: AuthGuardProps) {
  const { user, isLoading, hasPermission, hasRole } = useAuth()
  const router = useRouter()

  useEffect(() => {
    if (!isLoading && !user) {
      router.push("/login")
    }
  }, [user, isLoading, router])

  if (isLoading) {
    return (
      <div className="flex h-screen items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    )
  }

  if (!user) {
    return null
  }

  // Check required permission
  if (requiredPermission && !hasPermission(requiredPermission.resource, requiredPermission.action)) {
    return (
      fallback || (
        <div className="flex h-screen items-center justify-center">
          <div className="text-center">
            <h2 className="text-2xl font-bold text-slate-900 dark:text-slate-100 mb-2">权限不足</h2>
            <p className="text-slate-600 dark:text-slate-400">您没有访问此页面的权限</p>
          </div>
        </div>
      )
    )
  }

  // Check required role
  if (requiredRole && !hasRole(requiredRole)) {
    return (
      fallback || (
        <div className="flex h-screen items-center justify-center">
          <div className="text-center">
            <h2 className="text-2xl font-bold text-slate-900 dark:text-slate-100 mb-2">角色权限不足</h2>
            <p className="text-slate-600 dark:text-slate-400">您的角色无法访问此页面</p>
          </div>
        </div>
      )
    )
  }

  return <>{children}</>
}
